package org.easydarwin.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by stamSuper on 2017/11/19.
 * 功能：
 */

public class JsonUtil {
    private static JsonUtil instance;
    private JsonUtil(){}
    public static JsonUtil getInstance(){
        if(null == instance){
            instance = new JsonUtil();
        }
        return instance;
    }


    public <T> List<T> fromString2List(String json , Class<T> cls){
        //Json的解析类对象
        JsonParser parser = new JsonParser();
        //将JSON的String 转成一个JsonArray对象
        JsonArray jsonArray = parser.parse(json).getAsJsonArray();

        Gson gson = new Gson();
        ArrayList<T> list = new ArrayList<T>();
        for (JsonElement ele:jsonArray) {
            T target = gson.fromJson(ele, cls);
            list.add(target);
        }
        return list;
    }

}
